<?php
/*
 +----------------------------------------------------------------------
 + Title        : TokenService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2020/5/8 9:53
 + Last-time    : 2020/5/8 9:53+ 86187
 + Desc         : TokenService
 +----------------------------------------------------------------------
*/


namespace app\admin\service;


use app\http\exception\ApiException;
use app\http\exception\WebAdminApiException;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use think\facade\Config;

class TokenService {

	public static function setToken($user) {
		if (!$user) {
			return false;
		}
		$signer = new Sha256();
		$token = (new Builder())->setIssuer(Config::get('token.issuer'))
		                        ->setAudience(Config::get('token.audience'))
		                        ->setId(Config::get('token.id'), true)//自定义标识
		                        ->setIssuedAt(time())//当前时间
		                        ->setExpiration(time() + Config::get('token.office_expire'))//token有效期时长
		                        ->set('user', $user)
		                        ->sign($signer, Config::get('token.salt'))
		                        ->getToken();
		$token = (string) $token;
		return $token;
	}

	/**
	 *
	 * @param $token
	 *
	 * @return mixed
	 * @throws ApiException
	 * @author : Randy_chen
	 * @Date   : 2020/5/8
	 * @Time   : 9:57
	 */
	public static function check($token) {
		try {
			$token = (new Parser())->parse((string) $token);
		} catch (\Exception $e) {
			throw new ApiException(1, $e->getMessage());

		}

		$signer = new Sha256();
		if (!$token->verify($signer, Config::get('token.salt'))) {
			throw new ApiException(1, '数据签名错误');
		}
		$validationData = new ValidationData();
		$validationData->setIssuer(Config::get('token.issuer'));
		$validationData->setAudience(Config::get('token.audience'));
		$validationData->setId(Config::get('token.id'));//自字义标识
		if ($token->validate($validationData) === false) {
			throw new ApiException(1, '签名数据校验失败');
		} else {
			return $token->getClaim('user');
		}
	}
}